package com.tsd.jxc.sale.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.common.controller.BaseController;
import com.tsd.core.annotation.CheckBind;
import com.tsd.core.constants.Constants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.jxc.sale.entity.JxcSaleQuotation;
import com.tsd.jxc.sale.entity.JxcSaleQuotationExt;
import com.tsd.jxc.sale.service.JxcSaleQuotationService;
import com.tsd.jxc.utils.JxcAutoApprovalUtil;
import com.tsd.jxc.vo.PrintVo;
import com.tsd.system.entity.SysUser;
import com.tsd.system.entity.SysUserExt;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：JxcSaleQuotation销售报价 控制层
 *
 * @author Hillpool
 * @date 2022/12/12 11:26:43
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "进销存-销售报价", description = "销售报价的API描述")
public class JxcSaleQuotationController extends BaseController {

    @Resource
    private JxcSaleQuotationService jxcSaleQuotationService;
    @Resource
    private SystemSettingService systemSettingService;

    @ApiOperation(value = "根据sid获取销售报价", notes = "根据sid获取销售报价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "销售报价sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getJxcSaleQuotationBySid.action", method = RequestMethod.POST)
    public HttpResult<JxcSaleQuotation> getJxcSaleQuotationBySid() {
        HttpResult<JxcSaleQuotation> hr = new HttpResult<JxcSaleQuotation>();
        try {
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            JxcSaleQuotationExt quotationExt = jxcSaleQuotationService.queryBySid(sid);
            hr.setData(quotationExt);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除销售报价", notes = "根据id删除销售报价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "销售报价sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteJxcSaleQuotations.action", method = RequestMethod.POST)
    public HttpResult<String> deleteJxcSaleQuotations() {
        HttpResult<String> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            jxcSaleQuotationService.deleteJxcSaleQuotations(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存销售报价", notes = "保存销售报价，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "销售报价", required = true, paramType = "body", dataType = "JxcSaleQuotation")
    })
    @ResponseBody
    @RequestMapping(value = "/saveJxcSaleQuotation.action", method = RequestMethod.POST)
    public HttpResult<Object> saveJxcSaleQuotation() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String json = JSON.toJSONString(map);
            JxcSaleQuotationExt quotationExt = JSON.parseObject(json, JxcSaleQuotationExt.class);
            jxcSaleQuotationService.saveJxcSaleQuotation(quotationExt, opUser);
            // 判断是否自动审核
            JxcAutoApprovalUtil.autoApproval("auto_approval_sale_quotation", () -> {
                jxcSaleQuotationService.changeJxcSaleQuotationAuditState(Collections.singletonList(quotationExt.getSid()), 1, opUser);
            });
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询销售报价", notes = "分页查询销售报价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findJxcSaleQuotations.action", method = RequestMethod.POST)
    public HttpResult<Object> findJxcSaleQuotations() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(8);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "code", "code", false, false);
            HlpUtils.copyDateRangeValue(map, params, "quotation_date", false);
            HlpUtils.copyStringValue(map, params, "client_sid", "client_sid", false, false);
            HlpUtils.copyDateRangeValue(map, params, "audit_date", false);
            HlpUtils.copyStringValue(map, params, "with_detail", "with_detail", false, false);
            PageBean page = new PageBean(map);
            if (map.containsKey(Constants.KEY_NO_PAGE)) {
                page = null;
            }
            List<JxcSaleQuotationExt> list = jxcSaleQuotationService.findJxcSaleQuotations(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 审核/反审核
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeJxcSaleQuotationAuditState.action", method = RequestMethod.POST)
    @CheckBind(person = true)
    public HttpResult<Object> changeJxcSaleQuotationAuditState() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Integer state = HlpUtils.getInteger(map, "state");
            super.checkEmpty(state, "请提供参数：state");
            if (!Arrays.asList(1, -1).contains(state)) {
                throw new HlpException("state值错误：1-审核、-1-反审核");
            }
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcSaleQuotationService.changeJxcSaleQuotationAuditState(sidList, state, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 生成销售订单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/genJxcSaleQuotation2SaleOrder.action", method = RequestMethod.POST)
    public HttpResult<Object> genJxcSaleOrder2OutBill() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            List<String> sidList = super.getParamsList(map, "sid_list", String.class, true);
            jxcSaleQuotationService.genJxcSaleQuotation2SaleOrder(sidList, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "打印获取销售报价单数据", notes = "打印获取销售报价单数据")
    @ResponseBody
    @RequestMapping(value = "/queryJxcSaleQuotationData4Print.action", method = RequestMethod.POST)
    public HttpResult<Object> queryJxcSaleQuotationData4Print() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUserExt opUser = super.getSysUser();
            List<String> sidList = super.getParamsList("sid_list", String.class, true);
            List<JxcSaleQuotationExt> list = jxcSaleQuotationService.queryJxcSaleQuotationData4Print(sidList);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                ListUtil.forEach(list, t -> setting.procDisplay(t, GlobalSetting.TYPE_CLIENT));
            }
            List<PrintVo> voList = ListUtil.map(list, t -> t.convert2Print(opUser));
            hr.setData(voList);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
